
Imports System
Imports System.IO
Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO
Imports _2bMatesSite.Controls

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for category_groups.
	''' </summary>
	Public Partial Class category_groups
		Inherits BaseWebPage
		Protected txtStartIndexHidden As System.Web.UI.WebControls.TextBox
		Protected txtnGroupsCountHidden As System.Web.UI.WebControls.TextBox

		Protected sCatName As String = ""
		Protected nGroupsCount As Double = 0
		Protected categoryGroups As New ArrayList()
		Protected sSortBy As String = Constants.GROUP_SORT_BY_MOST_RECENT
		Protected catID As Integer = -1

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' this.pageTemplate.PageTitle = PageTitles.CATEGORY_GROUPS_PAGE;

			Dim usr As User = LoggedUser
			If usr = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			' init page from XML
			Me.initPageTitles(Constants.CATEGORY_GROUPS, "", Form1, Nothing, Nothing)
			Me.initAdvertisements(Form1, Nothing)

			If Constants.SHOW_GROUPS <> Constants.SHOW_ON Then
				Throw New Exception(Constants.ERROR_MESSAGE_NO_ACCESS)
			End If

			Dim cat As Categories.Category = Nothing

			If Request.Params(Constants.CATEGORY_PARAM) = Nothing OrElse Request.Params(Constants.CATEGORY_PARAM) = "" Then
				Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
			End If

			' init tabs
			ucGroupTabs.ActiveTab = 2
			ucGroupTabs.PageName = Constants.CATEGORY_GROUPS

			' get category ID
			Try
				catID = Convert.ToInt32(Request.Params(Constants.CATEGORY_PARAM))
			Catch
				Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
			End Try

			' get Category
			cat = Constants.CATEGORIES.GetCategoryByID(catID)
			If cat = Nothing Then
				Throw New Exception(Constants.ERROR_MESSAGE_CATEGORY_DOESNT_EXIST_ERROR)
			End If

			'init sort by param
			If Request.Params(Constants.GROUP_SORT_BY_PARAM) <> Nothing AndAlso Request.Params(Constants.GROUP_SORT_BY_PARAM) <> "" Then
				sSortBy = Request.Params(Constants.GROUP_SORT_BY_PARAM)
			End If

			' check if the value is valid, if not - init woth default value: Most Recent
			If sSortBy <> Constants.GROUP_SORT_BY_MOST_RECENT AndAlso sSortBy <> Constants.GROUP_SORT_BY_NAME AndAlso sSortBy <> Constants.GROUP_SORT_BY_POPULARITY Then
				sSortBy = Constants.GROUP_SORT_BY_MOST_RECENT
			End If

			sCatName = cat.Name
			litCategoryName.Text = sCatName
			categoryGroups = Groups.LoadCategoryGroups(cat.ID, sSortBy)
			nGroupsCount = categoryGroups.Count
			If nGroupsCount = 0 Then
				tblGroups.Visible = False
				lblNoGroups.Visible = True
			Else
				' init SortBy Links visibility, when sort functionality is added
				Select Case sSortBy
					Case Constants.GROUP_SORT_BY_POPULARITY
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbPopularity.Visible = False
						lblPopularity.Visible = True
						lbName.Visible = True
						lblName.Visible = False
						Exit Select
					Case Constants.GROUP_SORT_BY_NAME
						lbMostRecent.Visible = True
						lblMostRecent.Visible = False
						lbPopularity.Visible = True
						lblPopularity.Visible = False
						lbName.Visible = False
						lblName.Visible = True
						Exit Select
					Case Constants.GROUP_SORT_BY_MOST_RECENT
						lbMostRecent.Visible = False
						lblMostRecent.Visible = True
						lbPopularity.Visible = True
						lblPopularity.Visible = False
						lbName.Visible = True
						lblName.Visible = False
						Exit Select
				End Select

				' init Pagers
				dgPager.RedirectPage = String.Format("{0}?{1}={2}&{3}={4}", Constants.CATEGORY_GROUPS, Constants.CATEGORY_PARAM, cat.ID, Constants.GROUP_SORT_BY_PARAM, sSortBy)
				'Constants.CATEGORY_GROUPS + "?" + Constants.CATEGORY_PARAM + "=" + cat.ID;
				dgPager.MaxPageNumber = Convert.ToInt32(Math.Ceiling(nGroupsCount / Constants.MAX_GRID_RESULTS_ON_PAGE))
				dgPagerUp.RedirectPage = String.Format("{0}?{1}={2}&{3}={4}", Constants.CATEGORY_GROUPS, Constants.CATEGORY_PARAM, cat.ID, Constants.GROUP_SORT_BY_PARAM, sSortBy)
				dgPagerUp.MaxPageNumber = Convert.ToInt32(Math.Ceiling(nGroupsCount / Constants.MAX_GRID_RESULTS_ON_PAGE))
				dgPager.Action = "-1"
				dgPagerUp.Action = "-1"

				' initialize listing literals

				dgPager.dgListing.TotalCount = Convert.ToInt32(nGroupsCount)
				dgPagerUp.dgListing.TotalCount = Convert.ToInt32(nGroupsCount)
				'dgListingUp.TotalCount = Convert.ToInt32(nGroupsCount);

				'initialize current page number
				If Convert.ToInt32(Request.Params("page")) = 0 OrElse dgPager.CurrentPageNumber = 1 Then
					dgPager.CurrentPageNumber = 1
					dgPagerUp.CurrentPageNumber = 1
					'txtStartIndexHidden.Text = "0";
					ViewState("StartIndex") = 0
				Else
					dgPager.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					dgPagerUp.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					'txtStartIndexHidden.Text = Convert.ToString(((dgPager.CurrentPageNumber-1) * Constants.MAX_GRID_RESULTS_ON_PAGE));
					ViewState("StartIndex") = (dgPager.CurrentPageNumber - 1) * Constants.MAX_GRID_RESULTS_ON_PAGE
				End If

				dgPager.PagesRest = dgPager.MaxPageNumber - dgPager.FirstPageNumber + 1
				dgPager.LastPageNumber = Math.Min(dgPager.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				dgPagerUp.PagesRest = dgPagerUp.MaxPageNumber - dgPagerUp.FirstPageNumber + 1
				dgPagerUp.LastPageNumber = Math.Min(dgPagerUp.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				If Not IsPostBack Then
					dgCategoryGroups.VirtualItemCount = Convert.ToInt32(nGroupsCount)
					BindGrid()
				End If
			End If
		End Sub

		Protected Function CreateDataSource() As ICollection
			Dim dt As New DataTable()

			If categoryGroups.Count <= 0 Then
				dgPager.FirstPageNumber = 1
				dgPager.LastPageNumber = 1
				dgPager.MaxPageNumber = 1
				dgPager.PagesRest = 1
				dgPager.dgListing.StartIndex = 0
				dgPager.dgListing.EndIndex = 0
				dgPagerUp.FirstPageNumber = 1
				dgPagerUp.LastPageNumber = 1
				dgPagerUp.MaxPageNumber = 1
				dgPagerUp.PagesRest = 1
				dgPagerUp.dgListing.StartIndex = 0
				dgPagerUp.dgListing.EndIndex = 0
				dgCategoryGroups.AllowSorting = False
			Else
				Dim startIndex As Integer = Convert.ToInt32(ViewState("StartIndex"))
				Dim endIndex As Integer = startIndex + Constants.MAX_GRID_RESULTS_ON_PAGE
				Dim t As Integer = 0
				Dim counter As Integer = 0
				endIndex = Math.Min(endIndex, Convert.ToInt32(nGroupsCount))
				t = (endIndex - startIndex)
				dgPager.dgListing.StartIndex = startIndex + 1
				dgPager.dgListing.EndIndex = endIndex
				dgPagerUp.dgListing.StartIndex = startIndex + 1
				dgPagerUp.dgListing.EndIndex = endIndex

				Dim pic As GroupPicture
				Dim dr As DataRow

				dt.Columns.Add(New DataColumn("GroupID", GetType(Integer)))
				dt.Columns.Add(New DataColumn("URL", GetType(String)))
				dt.Columns.Add(New DataColumn("GroupImg", GetType(String)))

				dt.Columns.Add(New DataColumn("GroupURL", GetType(String)))
				dt.Columns.Add(New DataColumn("Name", GetType(String)))
				dt.Columns.Add(New DataColumn("Public", GetType(String)))
				dt.Columns.Add(New DataColumn("About", GetType(String)))
				dt.Columns.Add(New DataColumn("JoinURL", GetType(String)))
				dt.Columns.Add(New DataColumn("Members", GetType(Integer)))
				dt.Columns.Add(New DataColumn("Date", GetType(String)))

				' List search results
				Dim curGroupCreationDate As DateTime
				For Each result As Group In categoryGroups
					If counter >= startIndex AndAlso counter < endIndex Then
						dr = dt.NewRow()
						curGroupCreationDate = result.CreationDate
						dr(0) = result.ID
						dr(1) = "../" + Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + result.ID
						pic = result.DefaultPicture
						If pic <> Nothing Then
							dr(2) = Pictures.GetPictureSrcFullURL(pic, True, "../")
						Else
							dr(2) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
						End If
						dr(3) = "../" + Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + result.ID
						dr(4) = result.Name
						dr(5) = IIf(result.PublicGroup,"Public","Private")
						If result.ShortAbout <> Nothing AndAlso result.ShortAbout.Length > 0 Then
							dr(6) = Server.HtmlEncode(getBeginning(result.ShortAbout, Constants.MAX_GROUP_POPULAR_LENGTH))
						Else
							dr(6) = "&nbsp;"
						End If
						dr(7) = "../" + Constants.CONFIRM_JOIN_GROUP + "?" + Constants.GROUP_PARAM + "=" + result.ID
						dr(8) = result.Members.Count
						dr(9) = Constants.ARR_MONTHS(curGroupCreationDate.Month - 1) + " " + curGroupCreationDate.Day + ", " + curGroupCreationDate.Year
						dt.Rows.Add(dr)
					End If
					System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
				Next
			End If
			Dim dv As New DataView(dt)
			Return dv
		End Function

		Protected Sub BindGrid()
			' init datagrid with database data ordered by "orederBy" param
			dgCategoryGroups.DataSource = CreateDataSource()
			dgCategoryGroups.DataBind()
		End Sub

		Private Sub dgCategoryGroups_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
			' Examine if the item created is the header item 
			Dim lit As ListItemType = e.Item.ItemType
			If ListItemType.Header = lit Then
				' Redirect the default header rendering method to our own method 
				e.Item.SetRenderMethodDelegate(New RenderMethod(NewRenderMethod))
			End If
		End Sub

		Private Sub NewRenderMethod(ByVal writer As HtmlTextWriter, ByVal ctl As Control)
			'  We don't need to write the <TR> tag
			'     because it's already written by the writer 
			'     so now we write the Most Popular Groups column 
			writer.Write("<TD class=""data_grid_header"" colspan=""2"" align=""left"" width=""70%"">" + sCatName + "</TD>" & Chr(10) & "")

			dgCategoryGroups.HeaderStyle.AddAttributesToRender(writer)

			'***  Render all the cells that was defined
			'     in design time, except the first 2 ones 
			'     because we already rendered them above
			Dim i As Integer = 2
			While i <= ctl.Controls.Count - 1
				ctl.Controls(i).RenderControl(writer)
				System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
			End While

			'  We don't need to write the </TR> close tag
			'  because the writer will do that for us
		End Sub

		Protected Sub lbMostRecent_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.CATEGORY_GROUPS + "?" + Constants.CATEGORY_PARAM + "=" + catID + "&" + Constants.GROUP_SORT_BY_PARAM + "=" + Constants.GROUP_SORT_BY_MOST_RECENT)
		End Sub

		Protected Sub lbPopularity_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.CATEGORY_GROUPS + "?" + Constants.CATEGORY_PARAM + "=" + catID + "&" + Constants.GROUP_SORT_BY_PARAM + "=" + Constants.GROUP_SORT_BY_POPULARITY)
		End Sub

		Protected Sub lbName_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Response.Redirect(Constants.CATEGORY_GROUPS + "?" + Constants.CATEGORY_PARAM + "=" + catID + "&" + Constants.GROUP_SORT_BY_PARAM + "=" + Constants.GROUP_SORT_BY_NAME)
		End Sub

		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler dgCategoryGroups.ItemCreated, AddressOf Me.dgCategoryGroups_ItemCreated
		End Sub
#End Region

		====================
        ' This public property was added by conversion wizard to allow the access of a protected, autogenerated member variable Form1.
		====================
        Public ReadOnly Property Form1() As System.Web.UI.HtmlControls.HtmlForm
            Get
                Return Migrated_Form1
            End Get
        End Property
        'set { Migrated_Form1 = value; }
    End Class
End Namespace






